package com.feishu.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.feishu.base.type.ClassificationTypeEnum;
import com.feishu.base.type.OutJsonTypeEnum;
import com.feishu.rpc.core.SendHttpServer;
import com.feishu.service.FeiShuCommonService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.session.TyAccountContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CustomListener(
        category = "飞书审核后改飞书状态接口监听",
        description = "飞书审核后改飞书状态接口"
)
public class FeishuAuditTaskListener implements ExecutionListener {

    @CustomListenerField(
            description = "飞书三方审批同步编码",
            defaultValue = "",
            required = true
    )
    private FixedValue synCode;

    @CustomListenerField(
            description = "飞书三方审批同步对象",
            defaultValue = "",
            required = true
    )
    private FixedValue synObject;

    @CustomListenerField(
            description = "审核对象（对象不同，页面不同）",
            defaultValue = "",
            required = true
    )
    private FixedValue audit;
    @CustomListenerField(
            description = "审核状态[APPROVED，REJECTED, TERMINATED]",
            defaultValue = "",
            required = true
    )
    private FixedValue auditStatus;
    @Override
    public void notify(DelegateExecution execution) {
        String workFlowContainerIdStr = execution.getProcessInstanceBusinessKey();
        BigInteger workFlowContainerId = new BigInteger(workFlowContainerIdStr);

        TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(TyplmWorkFlowContainerService.class);
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(workFlowContainerId);

        if (workFlowContainerView instanceof WorkFlowObjectPackage) {
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            if (workFlowObjectPackage.getFlowObjectList() != null && workFlowObjectPackage.getFlowObjectList()
                    .size() != 0) {

                FlowObject flowObject = null;
                for(int i=0;i<workFlowObjectPackage.getFlowObjectList().size();i++){
                    flowObject=workFlowObjectPackage.getFlowObjectList().get(i);
                    String oType = flowObject.getRefObjectOtype();
                    if("ty.inteplm.part.CTyPart".equals(oType)){
                        break;
                    }
                    else if("ty.inteplm.form.CTyFormData".equals(oType)){
                        break;
                    }
                }

                SendHttpServer sendHttpServer = SpringUtil.getBean(SendHttpServer.class);
                TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);

                Map<String,Object> threadMap=new HashMap<>();

                threadMap.put("synCode",this.synCode.getExpressionText());
                threadMap.put("synObject",this.synObject.getExpressionText());
                threadMap.put("audit",this.audit.getExpressionText());
                threadMap.put("auditStatus",this.auditStatus.getExpressionText());

                String taskId= (String) execution.getVariable("taskId");
                String approval_code= (String) execution.getVariable("approval_code");
                String plmUserId= (String) execution.getVariable("plmUserId");

                execution.removeVariable("taskId");
                execution.removeVariable("approval_code");
                execution.removeVariable("plmUserId");


                threadMap.put("instance_id",execution.getProcessInstanceId());
                threadMap.put("start_time",System.currentTimeMillis());
                threadMap.put("end_time",System.currentTimeMillis());



                threadMap.put("code",workFlowContainerView.getCode());
                threadMap.put("name",workFlowContainerView.getName());
                threadMap.put("creatorAccount",workFlowContainerView.getCreatorAccount());
                threadMap.put("workFlowName",workFlowContainerView.getWorkFlowName());
                threadMap.put("emergencyDegreeName",workFlowContainerView.getEmergencyDegreeName());

                threadMap.put("taskId",taskId);
                threadMap.put("processInstanceId",execution.getProcessInstanceId());
                threadMap.put("activityId",execution.getCurrentActivityId());
                threadMap.put("workFlowContainerId",workFlowContainerId.toString());

                UserDO plmUserDO =null;
                if(plmUserId!=null && "null".equals(plmUserId)==false){
                    plmUserDO = typlmUserService.queryUserByKey(new BigInteger(plmUserId));
                }
                else{
                    plmUserDO=TyAccountContext.getUser();
                }
                threadMap.put("plmUserId",plmUserDO.getOid().toString());
                String executionstrategyStr=(String) execution.getVariable("executionstrategy");
                JSONArray executionstrategyList=JSONArray.parseArray(executionstrategyStr);
                JSONObject executionstrategy=null;
                if(executionstrategyList.size()>0){
                    String elementText=executionstrategyList.getJSONObject(0).getString("elementText");
                    executionstrategy=JSONObject.parseObject(elementText);
                    threadMap.put("executionstrategy",executionstrategy);

                }

                if("无策略".equals(executionstrategy.getString("name"))){
                    FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                    Map<String,Object> selectMap=new HashMap<>();
                    selectMap.put("processInstanceId",execution.getProcessInstanceId());
                    List<Map<String,Object>> feishuCodeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                    if(feishuCodeList.size()>0){
                        if(approval_code==null){
                            approval_code= (String) feishuCodeList.get(0).get("approval_code");
                        }
                        threadMap.put("submitId",feishuCodeList.get(0).get("submit_id"));
                    }
                    threadMap.put("feishuCodeList",feishuCodeList);

                }
                else if("一票决策".equals(executionstrategy.getString("name"))){
                    FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                    Map<String,Object> selectMap=new HashMap<>();
                    selectMap.put("processInstanceId",execution.getProcessInstanceId());
                    List<Map<String,Object>> feishuCodeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                    if(feishuCodeList.size()>0){
                        if(approval_code==null){
                            approval_code= (String) feishuCodeList.get(0).get("approval_code");
                        }
                        threadMap.put("submitId",feishuCodeList.get(0).get("submit_id"));
                    }
                    threadMap.put("feishuCodeList",feishuCodeList);
                }
                else{
                    if(approval_code==null){
                        FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                        Map<String,Object> selectMap=new HashMap<>();
                        selectMap.put("taskId",taskId);
                        List<Map<String,Object>> codeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                        if(codeList.size()>0){
                            approval_code= (String) codeList.get(0).get("approval_code");
                        }
                    }
                }



                threadMap.put("approval_code",approval_code);

                List<String> phones=new ArrayList<>();
                phones.add(plmUserDO.getTelephone());

                JSONArray feishuList=sendHttpServer.getUserIdDataToServer(this.synCode.getExpressionText(),
                                                                          this.synObject.getExpressionText(),
                                                                          OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                          ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"), phones);
                for(int i=0;i<feishuList.size();i++){
                    if(plmUserDO.getTelephone().equals(feishuList.getJSONObject(i).getString("mobile"))){
                        threadMap.put("entityApprovalId",feishuList.getJSONObject(i).getString("user_id"));
                        break;
                    }
                }

                JSONObject resultHttp=sendHttpServer.sendUserDataToChangeServer(this.synCode.getExpressionText(),
                                                                     this.synObject.getExpressionText(),
                                                                     OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                     ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"),
                                                                     flowObject,threadMap);

                if(resultHttp.containsKey("code")==false){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp);
                }
                if(resultHttp.getLongValue("code")!=0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp.getString("msg"));
                }
            }
        }
        else if(workFlowContainerView instanceof FlowChgFormView){
            FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
            if(flowChgFormView.getChgFormVO().getEcAffectVOS()!=null){
                List<FlowObject> flowObjectList=new ArrayList<>();
                for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                    ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                    BigInteger partOid = ecObjData.getRefObjectOid();
                    String oType = ecObjData.getRefObjectOtype();
                    FlowObject flowObject=new FlowObject();
                    flowObject.setRefObjectOid(partOid);
                    flowObject.setRefObjectOtype(oType);
                    flowObjectList.add(flowObject);
                }

                FlowObject flowObject = null;

                for(int i=0;i<flowObjectList.size();i++){
                    flowObject=flowObjectList.get(i);
                    String oType = flowObject.getRefObjectOtype();
                    if("ty.inteplm.part.CTyPart".equals(oType)){
                        break;
                    }
                    else if("ty.inteplm.form.CTyFormData".equals(oType)){
                        break;
                    }
                }
                SendHttpServer sendHttpServer = SpringUtil.getBean(SendHttpServer.class);
                TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);

                Map<String,Object> threadMap=new HashMap<>();

                threadMap.put("synCode",this.synCode.getExpressionText());
                threadMap.put("synObject",this.synObject.getExpressionText());
                threadMap.put("audit",this.audit.getExpressionText());
                threadMap.put("auditStatus",this.auditStatus.getExpressionText());

                String taskId= (String) execution.getVariable("taskId");
                String approval_code= (String) execution.getVariable("approval_code");
                String plmUserId= (String) execution.getVariable("plmUserId");

                execution.removeVariable("taskId");
                execution.removeVariable("approval_code");
                execution.removeVariable("plmUserId");


                if(approval_code==null){
                    FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                    Map<String,Object> selectMap=new HashMap<>();
                    selectMap.put("taskId",taskId);
                    List<Map<String,Object>> codeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                    if(codeList.size()>0){
                        approval_code= (String) codeList.get(0).get("approval_code");
                    }
                }

                threadMap.put("instance_id",taskId);
                threadMap.put("start_time",System.currentTimeMillis());
                threadMap.put("end_time",System.currentTimeMillis()+1000*60*60*24*7);



                threadMap.put("code",workFlowContainerView.getCode());
                threadMap.put("name",workFlowContainerView.getName());
                threadMap.put("creatorAccount",workFlowContainerView.getCreatorAccount());
                threadMap.put("workFlowName",workFlowContainerView.getWorkFlowName());
                threadMap.put("emergencyDegreeName",workFlowContainerView.getEmergencyDegreeName());

                threadMap.put("taskId",taskId);
                threadMap.put("approval_code",approval_code);

                UserDO taskUserDO = typlmUserService.queryUserByKey(flowChgFormView.getCreatorOid());
                UserDO plmUserDO =null;
                if(plmUserId!=null && "null".equals(plmUserId)==false){
                    plmUserDO = typlmUserService.queryUserByKey(new BigInteger(plmUserId));
                }
                else{
                    plmUserDO=TyAccountContext.getUser();
                }
                threadMap.put("plmUserId",plmUserDO.getOid().toString());

                List<String> phones=new ArrayList<>();
                phones.add(taskUserDO.getTelephone());
                if(taskUserDO.getTelephone().equals(plmUserDO.getTelephone())==false){
                    phones.add(plmUserDO.getTelephone());

                }

                JSONArray feishuList=sendHttpServer.getUserIdDataToServer(this.synCode.getExpressionText(),
                                                                          this.synObject.getExpressionText(),
                                                                          OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                          ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"), phones);

                for(int i=0;i<feishuList.size();i++){
                    if(taskUserDO.getTelephone().equals(feishuList.getJSONObject(i).getString("mobile"))){
                        threadMap.put("submitId",feishuList.getJSONObject(i).getString("user_id"));
                        break;
                    }
                }
                for(int i=0;i<feishuList.size();i++){
                    if(plmUserDO.getTelephone().equals(feishuList.getJSONObject(i).getString("mobile"))){
                        threadMap.put("approvalId",feishuList.getJSONObject(i).getString("user_id"));
                        break;
                    }
                }

                JSONObject resultHttp=sendHttpServer.sendUserDataToChangeServer(this.synCode.getExpressionText(),
                                                                                this.synObject.getExpressionText(),
                                                                                OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                                ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"),
                                                                                flowObject,threadMap);
                if(resultHttp.containsKey("code")==false){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp);
                }
                if(resultHttp.getLongValue("code")!=0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp.getString("msg"));
                }

            }
            else if(flowChgFormView.getChgFormVO().getEcObjDataVOS()!=null){
                List<FlowObject> flowObjectList=new ArrayList<>();
                for (int i = 0; i < flowChgFormView.getChgFormVO().getEcObjDataVOS().size(); i++) {
                    ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcObjDataVOS().get(i);
                    BigInteger partOid = ecObjData.getOid();
                    String oType = ecObjData.getOtype();
                    FlowObject flowObject=new FlowObject();
                    flowObject.setRefObjectOid(partOid);
                    flowObject.setRefObjectOtype(oType);
                    flowObjectList.add(flowObject);
                }

                FlowObject flowObject = flowObjectList.get(0);
                SendHttpServer sendHttpServer = SpringUtil.getBean(SendHttpServer.class);
                TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);

                Map<String,Object> threadMap=new HashMap<>();

                threadMap.put("synCode",this.synCode.getExpressionText());
                threadMap.put("synObject",this.synObject.getExpressionText());
                threadMap.put("audit",this.audit.getExpressionText());
                threadMap.put("auditStatus",this.auditStatus.getExpressionText());

                String taskId= (String) execution.getVariable("taskId");
                String approval_code= (String) execution.getVariable("approval_code");
                String plmUserId= (String) execution.getVariable("plmUserId");

                execution.removeVariable("taskId");
                execution.removeVariable("approval_code");
                execution.removeVariable("plmUserId");


                if(approval_code==null){
                    FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                    Map<String,Object> selectMap=new HashMap<>();
                    selectMap.put("taskId",taskId);
                    List<Map<String,Object>> codeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                    if(codeList.size()>0){
                        approval_code= (String) codeList.get(0).get("approval_code");
                    }
                }



                threadMap.put("instance_id",taskId);
                threadMap.put("start_time",System.currentTimeMillis());
                //threadMap.put("end_time",System.currentTimeMillis()+1000*60*60*24*7);
                threadMap.put("end_time",System.currentTimeMillis());



                threadMap.put("code",workFlowContainerView.getCode());
                threadMap.put("name",workFlowContainerView.getName());
                threadMap.put("creatorAccount",workFlowContainerView.getCreatorAccount());
                threadMap.put("workFlowName",workFlowContainerView.getWorkFlowName());
                threadMap.put("emergencyDegreeName",workFlowContainerView.getEmergencyDegreeName());

                threadMap.put("taskId",taskId);
                threadMap.put("approval_code",approval_code);

                UserDO taskUserDO = typlmUserService.queryUserByKey(flowChgFormView.getCreatorOid());
                UserDO plmUserDO =null;
                if(plmUserId!=null && "null".equals(plmUserId)==false){
                    plmUserDO = typlmUserService.queryUserByKey(new BigInteger(plmUserId));
                }
                else{
                    plmUserDO=TyAccountContext.getUser();
                }
                threadMap.put("plmUserId",plmUserDO.getOid().toString());

                List<String> phones=new ArrayList<>();
                phones.add(taskUserDO.getTelephone());
                if(taskUserDO.getTelephone().equals(plmUserDO.getTelephone())==false){
                    phones.add(plmUserDO.getTelephone());

                }

                JSONArray feishuList=sendHttpServer.getUserIdDataToServer(this.synCode.getExpressionText(),
                                                                          this.synObject.getExpressionText(),
                                                                          OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                          ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"), phones);

                for(int i=0;i<feishuList.size();i++){
                    if(taskUserDO.getTelephone().equals(feishuList.getJSONObject(i).getString("mobile"))){
                        threadMap.put("submitId",feishuList.getJSONObject(i).getString("user_id"));
                        break;
                    }
                }
                for(int i=0;i<feishuList.size();i++){
                    if(plmUserDO.getTelephone().equals(feishuList.getJSONObject(i).getString("mobile"))){
                        threadMap.put("approvalId",feishuList.getJSONObject(i).getString("user_id"));
                        break;
                    }
                }

                JSONObject resultHttp=sendHttpServer.sendUserDataToChangeServer(this.synCode.getExpressionText(),
                                                                                this.synObject.getExpressionText(),
                                                                                OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                                ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"),
                                                                                flowObject,threadMap);
//                if(resultHttp.containsKey("code")==false){
//                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp);
//                }
//                if(resultHttp.getLongValue("code")!=0){
//                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp.getString("msg"));
//                }

            }

        }

    }
}
